using B.S.Medical.Api.Read.Application.Command.Home;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Medical;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Home
{
    public class GetDailyRegistersHandler : IRequestHandler<GetDailyRegistersCommand, ApiResult<List<DailyRegisterDto>>>
    {
        private readonly IBaseRepository<RegisterModel> _registerRepo;

        public GetDailyRegistersHandler(IBaseRepository<RegisterModel> registerRepo)
        {
            _registerRepo = registerRepo;
        }

        public async Task<ApiResult<List<DailyRegisterDto>>> Handle(GetDailyRegistersCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<DailyRegisterDto>>();
            try
            {
                var result = new List<DailyRegisterDto>();
                var today = DateTime.Today;

                // 获取近7天的数据
                for (int i = 6; i >= 0; i--)
                {
                    var date = today.AddDays(-i);
                    var nextDate = date.AddDays(1);

                    var registerCount = _registerRepo.GetAll()
                        .Where(x => !x.IsDeleted && x.CreateTime >= date && x.CreateTime < nextDate)
                        .Count();

                    result.Add(new DailyRegisterDto
                    {
                        Date = date.ToString("M月d日"), // 格式化为 "1月1日" 格式
                        RegisterCount = registerCount
                    });
                }

                res.Data = result;
                res.Msg = "获取每日挂号数据成功!";
                res.Code = ApiEnum.Success;
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Msg = "获取每日挂号数据异常：" + ex.Message;
                res.Code = ApiEnum.Error;
            }
            return await Task.FromResult(res);
        }
    }
} 